--- 203 SHT30温湿度 modbus 9600,N,8,1
module(..., package.seeall)

local logtag = "SHT30"
local dtu, udtu ,uid ={}, {},3 -- 配置文件
local devices={{0},{0},{3,'气温/湿'},{4,'仓温/湿'}}
local ecode = 0
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    sys.taskInit(init)
end
local function flushData()
    local data = {
        devices[1][3] or 0,  devices[1][4] or 0,devices[2][3] or 0,  devices[2][4] or 0,
        devices[3][3] or 0,  devices[3][4] or 0,devices[4][3] or 0,  devices[4][4] or 0,ecode
       }
    usrdata.update(data)
end
local function _pro(d)
    local strcrc = pack.pack('<h', crypto.crc16("MODBUS", d:sub(1,-3)))
    if strcrc == d:sub(-2) then
        local nextpos, dev = pack.unpack(d, "b", 1)
        log.info("读取设备",dev)
        if dev == 1 or dev == 2 then
            local idx, val = pack.unpack(d:sub(4, 5), ">H")
            if val and dev==2 then val = val / 10 end --氧气有一个小数
            lcd.LCD_DATA[3] = devices[dev][2] ..":".. val
            devices[dev][3] = val
        elseif dev == 3 or dev == 4 then
            local idx, wd, sd = pack.unpack(d:sub(4, 7), ">hh")
            wd = wd / 10
            sd = sd / 10
            devices[dev][3]=wd
            devices[dev][4]=sd
            lcd.LCD_DATA[3] = devices[dev][2] .. wd .. ',' .. sd
        end
        ecode = bit.clear(ecode,dev-1)
        flushData()
    else 
        lcd.LCD_DATA[3] = logtag.." 数据校验错误"
    end
end
local function err(id)
    lcd.LCD_DATA[3] = id..(devices[id][2] or logtag).." 故障"
    ecode = bit.set(ecode,id-1)
    flushData()
end
local function read(dev)
    local result, data = sys.waitUntil("UART_READ_DONE_NEXT_" .. uid, 1000)
    if result then
        if data then
            _pro(data)
        end
        power.SET_QC(9,0)
    else
        err(dev[1])
        if udtu.beep and udtu.beep==1 then sys.publish("SYS_BEEP",1000) end
        power.SET_QC(9,1)
    end
end
function init()
    sys.wait(100)
    while true do
        for key, value in pairs(devices) do
            if value[1] == 1 or value[1] == 2 then
                tools.modbus_send(uid, value[1], 3, 0x6001, 1)
                read(value)
                sys.wait(500)
            elseif value[1] == 3 or value[1] == 4 then
                tools.modbus_send(uid, value[1], 3, 0, 2)
                read(value)
                sys.wait(500)
            end
        end
    end
end
